package com.wyclabs.auth.common;

import com.wyclabs.auth.common.properties.ClientProperties;
import com.wyclabs.auth.common.properties.SecurityProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.builders.ClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;

import java.util.List;

/**
 * 客户端注册
 * @author sr
 * @date 2019/11/07
 */
public class ClientRegisterUtil {
    /**
     * 客户端注册
     * @param clients            客户端配置
     * @param securityProperties 客户端相关信息
     * @param passwordEncoder    密码加密工具
     */
    public static void register(ClientDetailsServiceConfigurer clients, SecurityProperties securityProperties, PasswordEncoder passwordEncoder) throws Exception {
        List<ClientProperties> modnimClients = securityProperties.getClients();
        int index = 0;
        InMemoryClientDetailsServiceBuilder memory = clients.inMemory();
        ClientDetailsServiceBuilder<InMemoryClientDetailsServiceBuilder> builder = null;
        for (ClientProperties client : modnimClients) {
            if (index == 0) {
                builder = memory.withClient(client.getClientId())
                        .secret(passwordEncoder.encode(client.getClientSecret()))
                        .authorizedGrantTypes(SecurityTokenGranter.grantTypes(client.getGrantTypeSet().toArray(new String[]{})))
                        .accessTokenValiditySeconds(securityProperties.getTokenProperties().getAccessTokenExpiredIn())
                        .refreshTokenValiditySeconds(securityProperties.getTokenProperties().getRefreshTokenExpiredIn())
                        .scopes(StringUtils.splitByWholeSeparatorPreserveAllTokens(client.getScope(), ",")).and();
            } else {
                builder = builder.withClient(client.getClientId())
                        .secret(passwordEncoder.encode(client.getClientSecret()))
                        .authorizedGrantTypes(SecurityTokenGranter.grantTypes(client.getGrantTypeSet().toArray(new String[]{})))
                        .accessTokenValiditySeconds(securityProperties.getTokenProperties().getAccessTokenExpiredIn())
                        .refreshTokenValiditySeconds(securityProperties.getTokenProperties().getRefreshTokenExpiredIn())
                        .scopes(StringUtils.splitByWholeSeparatorPreserveAllTokens(client.getScope(), ",")).and();
            }
            index++;
        }
    }
}
